package com.baizhi.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Controller
@RequestMapping("file")
public class FileController {

    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Value("${file.download.dir}")
    private String realPath;//下载哪个目录中的文件

    /**
     * 文件下载
     *      1. 读取目标文件，获取其输入流
     *      2. 设置响应头："content-disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8")
     *      3. 设置响应流（将前面的文件输入流复制到响应流中）
     */
    @GetMapping("/download")
    public void download(String fileName, HttpServletResponse resp) throws IOException {
        log.info("待下载的文件:" + fileName);
        resp.setHeader("content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
        ServletOutputStream os = resp.getOutputStream();
        FileInputStream fis = new FileInputStream(new File(realPath,fileName));
        FileCopyUtils.copy(fis, os);
        log.info("下载成功");
    }

}
